package org.simpatia;


import java.io.File;
import java.lang.instrument.Instrumentation;
import java.util.concurrent.CountDownLatch;

public class Agent {
    public static void main(String... args) {
        startContainer(args.length == 1 && args[0] != null ? args[0] : null, null);
    }

    public static void premain(final String agentArgs, final Instrumentation inst) {
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread() {
            public void run() {
                startContainer(agentArgs, inst);
                latch.countDown();
            }
        }.start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void startContainer(String agentArgs, Instrumentation inst) {
        try {
            AgentClassLoader classLoader;
            if(agentArgs == null) {
                classLoader = new AgentClassLoader();
            } else {
                String simpatiaHome = agentArgs;
                classLoader = new AgentClassLoader(simpatiaHome);
            }

            Thread.currentThread().setContextClassLoader(classLoader);
            Class clazz = classLoader.loadClass("org.simpatia.SimpatiaContainer");

            String defaultConfigLocation = "simpatia-config.json";
            String configLocation;

            //[ try to get from properties
            configLocation = System.getProperty("simpatia.config.location");
            //]

            //[ try to load from home
            if(configLocation == null) {
                File config = new File( classLoader.getSimpatiaHome() + "/" + defaultConfigLocation );
                if(config.exists()) {
                    configLocation = config.getPath();
                }
            }
            //]

            //[ default location
            if(configLocation == null) {
                configLocation = defaultConfigLocation;
            }
            //]

            Object container = clazz.newInstance();
            container.getClass().getMethod(
                    "start", String.class, Instrumentation.class, String.class
            ).invoke(container, agentArgs, inst, configLocation);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
